package cn.stylefeng.guns.modular.system.controller;

import cn.stylefeng.guns.config.ImgConfig;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import cn.stylefeng.guns.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import cn.stylefeng.guns.modular.system.model.Person;
import cn.stylefeng.guns.modular.system.service.IPersonService;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 失信人控制器
 *
 * @author fengshuonan
 * @Date 2020-07-18 14:34:48
 */
@Controller
@RequestMapping("/person")
public class PersonController extends BaseController {

    private String PREFIX = "/system/person/";

    private List<String> REGION_URLS = Arrays.asList("DL","PS");

    @Value("${guns.file-upload-path}")
    private String tmpPath;

    @Autowired
    private IPersonService personService;
    @Autowired
    private ImgConfig imgConfig;
    /**
     * 跳转到失信人首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "person.html";
    }

    /**
     * 跳转到添加失信人
     */
    @RequestMapping("/person_add")
    public String personAdd() {
        return PREFIX + "person_add.html";
    }

    /**
     * 跳转到修改失信人
     */
    @RequestMapping("/person_update/{personId}")
    public String personUpdate(@PathVariable Integer personId, Model model) {
        Person person = personService.selectById(personId);
        model.addAttribute("item",person);
        LogObjectHolder.me().set(person);
        return PREFIX + "person_edit.html";
    }

    /**
     * 获取失信人列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        EntityWrapper<Person> entityWrapper = new EntityWrapper<>();
        Wrapper<Person> like = entityWrapper
                .or().like("name",condition)
                .or().like("caseNumber",condition)
                .or().like("identificationNumber",condition)
                .or().like("age",condition)
                .or().like("address",condition)
                .or().like("outstandingAmount",condition)
                .or().like("imgUrl",condition)
                .or().like("region",condition)
                .orderBy("id",false);
        return personService.selectList(like);
    }

    /**
     * 新增失信人
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(@RequestParam("img") MultipartFile file, Person person) {
        if (file.isEmpty()){
            throw new ServiceException(500,"上传的文件不能为空");
        }
        judgeRegion(file, person);
        personService.insert(person);
        return SUCCESS_TIP;
    }

    /**
     * 删除失信人
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer personId,@RequestParam String personImgUrl) {
        personService.deleteById(personId);
        String staticUrl = personImgUrl.replaceAll("/static", tmpPath);
        imgConfig.deleteFileByUrl(staticUrl);
        return SUCCESS_TIP;
    }

    /**
     * 修改失信人
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(@RequestParam("img") MultipartFile file,Person person) {
        String oldUrl = person.getImgUrl();
        Person person1 = personService.selectById(person.getId());
        String oldImgNameUrl;
        //1.判断是否为空
        //2.判断区域是否变化 变化转移文件
        // 文件如果为空 判断区域是否变化 变化改数据库转移文件 没变 只改数据库
        //如果文件不为空 证明修改了图片 什么都改
        if (file.isEmpty()){
            if (person.getRegion().equals(person1.getRegion())){
                personService.updateById(person);
            }else {
                //老地址
                oldImgNameUrl = oldUrl.replaceAll("/static", tmpPath);
                String newImgNameUrl;
                for (String region : REGION_URLS) {
                    //新地址
                    if (region.equals(person.getRegion())){
                      newImgNameUrl = oldImgNameUrl.replaceAll(person1.getRegion(),person.getRegion());
                        File oldFile = new File(oldImgNameUrl);
                        File newFile = new File(newImgNameUrl);
                        // 判断路径是否存在，不存在则新创建一个
                        if (!newFile.getParentFile().exists()) {
                            newFile.getParentFile().mkdirs();
                        }
                        String newUrl = oldUrl.replaceAll(person1.getRegion(),person.getRegion());
                        person.setImgUrl(newUrl);
                        personService.updateById(person);
                        oldFile.renameTo(newFile);
                    }
                }
            }
        }else {
            judgeRegion(file, person);
            personService.updateById(person);
            for (String region : REGION_URLS) {
                if (region.equals(person.getRegion())) {
                    oldImgNameUrl = oldUrl.replaceAll("/static", tmpPath);
                    imgConfig.deleteFileByUrl(oldImgNameUrl);
                }
            }
        }
        return SUCCESS_TIP;
    }
    /**
     * 失信人详情
     */
    @RequestMapping(value = "/detail/{personId}")
    @ResponseBody
    public Object detail(@PathVariable("personId") Integer personId) {
        return personService.selectById(personId);
    }

    /**
     * @param file 传入的img
     * @param person person对象
     */
    private void judgeRegion(@RequestParam("img") MultipartFile file, Person person) {
        for (String region : REGION_URLS) {
            if (region.equals(person.getRegion())){
                String staticUrl = imgConfig.writeFile(file,"/"+region+"/");
                person.setImgUrl(staticUrl);
                return;
            }
        }
        throw new ServiceException(500,"超出区域范围");
    }
}
